package com.mentalhealthplatform.utils.stringUtils;

import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

@Component
public class EmptyStringToNullResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        // 判断参数是否有 @RequestParam 和 @ConvertEmptyToNull 注解
        return parameter.hasParameterAnnotation(RequestParam.class) &&
                parameter.hasParameterAnnotation(ConvertEmptyToNull.class) &&
                String.class.equals(parameter.getParameterType());
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        String paramName = parameter.getParameterName();
        String paramValue = webRequest.getParameter(paramName);

        if (paramValue != null && paramValue.isEmpty()) {
            return null;
        }

        return paramValue;
    }

}
